<template>
  <div class="diagnostic-system">
    <!-- 文件上传区域 -->
    <FileUpload :isProcessing="isProcessing" @fileSelected="handleFileSelected" @fileRemoved="handleFileRemoved"
      @recognize="handleRecognition" @typeChange="handleTypeChange" @error="handleError" />

    <!-- 错误消息显示 -->
    <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>

    <!-- 识别结果展示 -->
    <RecognitionResult :passage="passage" />

    <!-- 分析报告展示区域 -->
    <AnalysisReport :reportData="reportData" :examTypeName="getSelectedExamTypeName()" />
  </div>
</template>

<script>
import { ref, nextTick } from "vue";
import { ocr } from "../API/api";
import userStore from "../store/userStore";
import FileUpload from "../components/OCR/FileUpload.vue";
import RecognitionResult from "../components/OCR/RecognitionResult.vue";
import AnalysisReport from "../components/OCR/AnalysisReport.vue";

export default {
  components: {
    FileUpload,
    RecognitionResult,
    AnalysisReport
  },
  setup() {
    const file = ref(null);
    const isProcessing = ref(false);
    const passage = ref("");
    const reportData = ref(null);
    const errorMessage = ref(null);

    const useuserSotor = userStore();

    // 文章类型选择
    const selectedExamType = ref('cet4_6'); // 默认选择 CET4/6
    const examTypes = ref([
      {
        value: 'primary',
        label: '小学作文',
        description: '小学阶段作文评估',
        icon: '🎒',
        status: 'stable'
      },
      {
        value: 'middle_school',
        label: '中学作文',
        description: '初高中作文评估',
        icon: '📚',
        status: 'stable'
      },
      {
        value: 'cet4_6',
        label: 'CET4/6',
        description: '大学英语四六级',
        icon: '🎓',
        status: 'stable'
      },
      {
        value: 'ielts_toefl',
        label: 'IELTS/TOEFL',
        description: '雅思托福考试',
        icon: '🌍',
        status: 'stable'
      },
      {
        value: 'civil_exam',
        label: '公务员考试',
        description: '公务员申论写作',
        icon: '🏛️',
        status: 'stable'
      }
    ]);

    // 获取选择的文章类型名称
    const getSelectedExamTypeName = () => {
      const selectedType = examTypes.value.find(type => type.value === selectedExamType.value);
      return selectedType ? selectedType.label : '作文分析报告';
    };

    // 清除之前的数据
    const clearPreviousData = () => {
      passage.value = "";
      reportData.value = null;
      errorMessage.value = null;
      useuserSotor.passage = "";
      useuserSotor.resData = null;
      console.log("清除之前的分析数据");
    };

    // 验证数据完整性
    const validateReportData = (data) => {
      if (!data || typeof data !== 'object') return false;
      // 基本验证，确保数据是对象即可
      return true;
    };

    // 处理OCR识别 - 完全重写，彻底清除缓存依赖
    const handleRecognition = async () => {
      if (!file.value) {
        errorMessage.value = "请先上传文件";
        return;
      }

      isProcessing.value = true;

      // 彻底清除所有数据，包括store中的数据
      passage.value = "";
      reportData.value = null;
      errorMessage.value = null;

      // 清除store中的所有数据
      useuserSotor.passage = "";
      useuserSotor.resData = null;
      useuserSotor.dispaly = false;
      useuserSotor.open = false;

      console.log("=== 开始新的识别流程 ===");
      console.log("当前选择的分析类型:", selectedExamType.value);
      console.log("已彻底清除所有缓存数据");

      try {
        // 第一步：OCR识别
        console.log("第一步：开始OCR识别...");
        const ocrResponse = await ocr.getOcrData(file.value);

        if (!ocrResponse?.data?.result) {
          throw new Error("OCR识别失败，请检查图片质量");
        }

        const recognizedText = ocrResponse.data.result;
        console.log("OCR识别成功，文本长度:", recognizedText.length);

        // 设置识别的文本
        passage.value = recognizedText;
        useuserSotor.passage = recognizedText;

        // 第二步：文章分析
        console.log(`第二步：开始分析文章 - 类型: ${ getSelectedExamTypeName() }`);
        console.log("发送到后端的参数:", {
          text: recognizedText.substring(0, 100) + "...",
          type: selectedExamType.value
        });

        // 确保完全等待异步处理完成
        const analysisResult = await useuserSotor.handlePassage(
          recognizedText,
          selectedExamType.value
        );

        console.log("=== OCR页面接收到的完整响应 ===");
        console.log("analysisResult:", analysisResult);
        console.log("analysisResult.status:", analysisResult?.status);
        console.log("analysisResult.data:", analysisResult?.data);
        console.log("analysisResult.data.result:", analysisResult?.data?.result);

        // 检查 UserStore 中的数据状态
        console.log("=== UserStore 数据状态检查 ===");
        console.log("useuserSotor.resData:", useuserSotor.resData);
        console.log("useuserSotor.resData 类型:", typeof useuserSotor.resData);
        console.log("useuserSotor.resData 是否为数组:", Array.isArray(useuserSotor.resData));

        if (!analysisResult?.data?.result) {
          throw new Error("后端分析服务返回数据格式错误");
        }

        // 第三步：处理返回数据 - 专门处理数组格式
        console.log("第三步：处理分析结果");

        // 使用 UserStore 中存储的数据
        let backendResult = useuserSotor.resData || analysisResult.data.result;

        console.log("=== 后端数据分析 ===");
        console.log("数据来源:", useuserSotor.resData ? "UserStore缓存" : "直接API响应");
        console.log("数据类型:", typeof backendResult);
        console.log("是否为数组:", Array.isArray(backendResult));
        console.log("期望的考试类型:", selectedExamType.value);

        if (Array.isArray(backendResult)) {
          console.log("数组长度:", backendResult.length);
          console.log("数组中的所有类型:", backendResult.map((item, index) => ({
            index,
            type: item.content?.meta_info?.exam_type || "未知"
          })));
        }

        let finalReportData = null;

        // 根据后端返回的数据结构进行处理
        if (typeof backendResult === 'object' && backendResult.meta_info) {
          // 如果直接返回的是分析结果对象
          console.log("检测到直接返回的分析结果对象");
          console.log("返回数据的exam_type:", backendResult.meta_info.exam_type);

          if (backendResult.meta_info.exam_type === selectedExamType.value) {
            finalReportData = backendResult;
            console.log("✅ 数据类型匹配，直接使用");
          } else {
            console.log("❌ 数据类型不匹配");
            console.log("期望类型:", selectedExamType.value);
            console.log("实际类型:", backendResult.meta_info.exam_type);
            throw new Error(`返回的分析类型(${ backendResult.meta_info.exam_type })与请求类型(${ selectedExamType.value })不匹配`);
          }
        } else if (Array.isArray(backendResult)) {
          // 处理数组格式 - 后端返回了多个类型的分析结果
          console.log("⚠️ 检测到数组格式，后端返回了多个分析结果");
          console.log("数组长度:", backendResult.length);

          // 详细分析每个数组项
          console.log("=== 数组内容分析 ===");
          backendResult.forEach((item, index) => {
            console.log(`数组项 ${ index }:`, {
              hasRole: !!item.role,
              hasContent: !!item.content,
              examType: item.content?.meta_info?.exam_type || "未知类型",
              totalScore: item.content?.overall_assessment?.total_score || "无分数",
              evalTime: item.content?.meta_info?.evaluation_time || "无时间"
            });
          });

          // 查找匹配当前选择类型的结果
          console.log(`\n=== 查找匹配类型: ${ selectedExamType.value } ===`);

          const matchedResult = backendResult.find(item => {
            const examType = item.content?.meta_info?.exam_type;
            console.log(`检查项目: ${ examType } === ${ selectedExamType.value } ?`, examType === selectedExamType.value);
            return item.content &&
              item.content.meta_info &&
              examType === selectedExamType.value;
          });

          if (matchedResult?.content) {
            finalReportData = matchedResult.content;
            console.log("✅ 成功找到匹配的分析结果");
            console.log("匹配结果预览:", {
              exam_type: finalReportData.meta_info.exam_type,
              total_score: finalReportData.overall_assessment?.total_score,
              evaluation_time: finalReportData.meta_info.evaluation_time
            });
          } else {
            console.log("❌ 未找到匹配的分析结果");
            console.log("可用的类型:", backendResult.map(item =>
              item.content?.meta_info?.exam_type || "未知"
            ));

            // 提供更详细的错误信息
            const availableTypes = backendResult
              .map(item => item.content?.meta_info?.exam_type)
              .filter(type => type)
              .join(', ');

            throw new Error(`后端返回了 ${ backendResult.length } 个分析结果，但没有找到 ${ getSelectedExamTypeName() }(${ selectedExamType.value }) 类型的结果。可用类型: ${ availableTypes }`);
          }
        } else {
          console.log("❌ 未知的数据格式");
          throw new Error("后端返回的数据格式不支持");
        }

        // 第四步：验证和显示数据
        if (!finalReportData || !validateReportData(finalReportData)) {
          throw new Error("分析结果数据不完整");
        }

        console.log("=== 最终显示的数据 ===");
        console.log("总分:", finalReportData.overall_assessment?.total_score);
        console.log("等级:", finalReportData.overall_assessment?.grade_level);
        console.log("评估时间:", finalReportData.meta_info?.evaluation_time);

        // 直接设置最终数据，不保存到store缓存
        reportData.value = finalReportData;

        // 清除store中的缓存，确保不影响下次请求
        useuserSotor.resData = null;

        await nextTick();
        console.log("✅ 分析完成，界面渲染成功");

      } catch (error) {
        console.error("=== 处理失败 ===");
        console.error("错误信息:", error.message);
        console.error("错误堆栈:", error.stack);

        errorMessage.value = error.message || "处理失败，请重试";
        reportData.value = null;

        // 确保清除所有数据
        useuserSotor.resData = null;
        useuserSotor.passage = "";
      } finally {
        isProcessing.value = false;
        console.log("=== 识别流程结束 ===");
      }
    };



    // 新的事件处理方法
    const handleFileSelected = (selectedFile) => {
      file.value = selectedFile;
      clearPreviousData();
      errorMessage.value = null;
    };

    const handleFileRemoved = () => {
      file.value = null;
      clearPreviousData();
    };

    const handleTypeChange = (type) => {
      selectedExamType.value = type;
      useuserSotor.content_type = type;

      // 切换类型时清除所有缓存数据，确保获取最新的分析结果
      reportData.value = null;
      errorMessage.value = null;
      useuserSotor.resData = null;

      console.log('选择的文章类型:', type, '已清除所有缓存数据，需要重新分析');
    };

    const handleError = (error) => {
      errorMessage.value = error;
    };

    return {
      isProcessing,
      reportData,
      errorMessage,
      passage,
      selectedExamType,
      examTypes,
      getSelectedExamTypeName,
      handleFileSelected,
      handleFileRemoved,
      handleRecognition,
      handleTypeChange,
      handleError,
    };
  },
};
</script>
<style scoped>
.diagnostic-system {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

.error-message {
  color: #ff6b6b;
  text-align: center;
  margin: 15px 0;
  font-weight: 500;
  padding: 15px;
  background-color: rgba(255, 107, 107, 0.1);
  border-radius: 8px;
  border-left: 4px solid #ff6b6b;
}

@media (max-width: 768px) {
  .diagnostic-system {
    padding: 15px;
  }
}
</style>